import { Module, ValidationPipe } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { RedisModule } from '@nestjs-modules/ioredis';
import { DataSource } from 'typeorm';

// import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './modules/app/user/user.module';
import { AnalyticsModule } from './modules/app/analytics/analytics.module';
import { MessageModule } from './modules/app/message/message.module';
import { PointModule } from './modules/app/point/point.module';
import { PunchModule } from './modules/app/punch/punch.module';
import { FoodModule } from './modules/app/food/food.module';
import { PunchFoodModule } from './modules/app/punch-food/punch-food.module';
import { UploadModule } from './modules/libs/upload/upload.module';

import { RedisCacheModule } from '@/core/redis/redis-cache.module';
import { JwtGuard } from '@/core/guards';
import { ResponseInterceptor } from '@/core/interceptors';
import { ExceptionsFilter } from '@/core/filters';
import { PostModule } from './modules/app/post/post.module';
import { TestModule } from './modules/app/test/test.module';
import { AppController } from './app.controller';
import { UserRelationModule } from './modules/app/user-relation/user-relation.module';
import { CategoryModule } from './modules/app/category/category.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // 使配置模块在整个应用程序中全局可用
      envFilePath:
        process.env.NODE_ENV === 'production'
          ? ['.env.production']
          : ['.env.local', '.env.production'],
      // 指定要加载的环境文件,前面的文件会覆盖前面的同名变量
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.get<string>('DATABASE_URL'),
        port: Number(configService.get<number>('DATABASE_PORT')),
        username: configService.get<string>('DATABASE_USERNAME'),
        password: configService.get<string>('DATABASE_PASSWORD'),
        // password: '',
        database: 'diet',
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        synchronize: true, // 是否自动同步数据库表结构，生产建议关闭
        // autoLoadEntities: true, // 自动加载实体
        logging: true, // 开启日志
        logger: 'debug', // 日志类型
        extra: {
          connectionLimit: 10, // 连接池大小
        },
        retryAttempts: 2,
      }),
    }),
    RedisModule.forRoot({
      type: 'single',
      url: 'redis://localhost:6379',
    }),
    UserModule,
    RedisCacheModule,
    FoodModule,
    PunchModule,
    PointModule,
    MessageModule,
    AnalyticsModule,
    PunchFoodModule,
    UploadModule,
    PostModule,
    TestModule,
    UserRelationModule,
    CategoryModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_PIPE,
      useFactory: () =>
        new ValidationPipe({
          transform: true, // 自动转换类型
          whitelist: false, // 移除多余字段
          forbidNonWhitelisted: false, // 禁止未定义字段
          transformOptions: {
            enableImplicitConversion: true, // 启用隐式转换
          },
        }),
    },
    {
      provide: APP_FILTER,
      useClass: ExceptionsFilter, //依赖注入方式注册的全局异常过滤器
    },
    {
      provide: APP_INTERCEPTOR,
      useClass: ResponseInterceptor, //依赖注入方式注册的全局响应拦截器
    },
    {
      provide: APP_GUARD,
      useClass: JwtGuard,
    },
  ],
})
export class AppModule {
  // 整个项目注入 TypeOrmModule
  constructor(
    private dataSource: DataSource,
    private configService: ConfigService,
  ) {}
}
